package com.wontube.smr.bo.player;

import java.io.IOException;
import java.util.List;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;

import com.wontube.client.utils.Base64;
import com.wontube.core.dao.mybatis.QueryExample;
import com.wontube.core.pub.AppEnvironment;
import com.wontube.smr.bo.pub.Mp3DownloadListenter;
import com.wontube.smr.client.model.po.Mp3Url;
import com.wontube.smr.client.model.po.VideoPage;
import com.wontube.smr.dao.mapper.Mp3UrlMapper;
import com.wontube.smr.dao.mapper.VideoPageMapper;
import com.wontube.smr.pub.DefaultDBHelper;






/**
 * @author yuechao
 *
 */
public class Mp3PlayerServlet extends HttpServlet {
	private static final long serialVersionUID = -5600111920059432700L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String pageUrl = req.getParameter("url");
		if (pageUrl == null || "".equals(pageUrl)) {
			return;
		}
		
		byte[] buffer = Base64.decode(pageUrl);
		pageUrl = new String(buffer, AppEnvironment.charsetName);

		VideoPage page;
		Mp3Url mp3Url;
		SqlSession session = DefaultDBHelper.getSqlSession(true);
		try {
			VideoPageMapper pageMapper = session.getMapper(VideoPageMapper.class);
			QueryExample ex = new QueryExample();
			ex.or().addCriterion("page_url=", pageUrl);
			List<VideoPage> pages = pageMapper.selectByExample(ex);
			if (pages.size() < 1) {
				return;
			}
			
			page = pages.get(0);
			Mp3UrlMapper mp3Mapper = session.getMapper(Mp3UrlMapper.class);
			ex = new QueryExample();
			ex.or().addCriterion("page_id=", page.getId());
			List<Mp3Url> mp3Urls = mp3Mapper.selectByExample(ex);
			if (mp3Urls.size() < 1) {
				return;
			}
			mp3Url = mp3Urls.get(0);
		} finally {
			session.close();
		}

		AsyncContext ac = req.startAsync();
		ac.setTimeout(10 * 60 * 60 * 1000); // 限10小时播放完成
		ac.start(new Mp3DownloadListenter(ac, page, mp3Url));
	}
}
